﻿using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using RG.Common.Export;

namespace RG.Common.WPF.Controls.SortableGridView
{
    public class ColumnInfoSort : IComparer
    {
        private List<IColumnInfo> Columns { get; set; }
        private List<ListSortDirection> Directions { get; set; }

        public ColumnInfoSort()
        {
            Columns = new List<IColumnInfo>();
            Directions = new List<ListSortDirection>();
        }

        public void AddColumn(IColumnInfo column, ListSortDirection direction)
        {
            Columns.Add(column);
            Directions.Add(direction);
        }

        public int Compare(object x, object y)
        {
            for(int i=0; i<Columns.Count; i++)
            {
                var v1 = Columns[i].GetValueForCompare(x);
                var v2 = Columns[i].GetValueForCompare(y);

                int cmp;
                if (v1 == null && v2 == null) cmp = 0;
                else if (v1 == null) cmp = -1;
                else if (v2 == null) cmp = 1;
                else cmp = v1.CompareTo(v2);

                if (cmp != 0)
                    return (Directions[i] == ListSortDirection.Ascending) ? cmp : -cmp;
            }
            return 0;
        }
    }
}
